#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

def is_code_file(filename):
    """检查是否为需要处理的代码文件"""
    code_extensions = ['.c', '.h', '.cpp', '.hpp']
    return any(filename.lower().endswith(ext) for ext in code_extensions)

def print_with_indent(message, level=0):
    """打印带缩进的消息"""
    indent = '  ' * level
    print(f"{indent}{message}")

def convert_file_encoding(file_path):
    """转换单个文件的编码"""
    try:
        # 先读取文件内容
        with open(file_path, 'r', encoding='gb2312') as f:
            content = f.read()
        
        # 直接用UTF-8编码写回原文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
        return True
    except UnicodeDecodeError:
        print_with_indent(f"警告: 无法以GB2312编码读取文件 {file_path}，可能不是GB2312编码或已经是UTF-8编码", 1)
        return False
    except Exception as e:
        print_with_indent(f"错误: 处理文件 {file_path} 时出错: {str(e)}", 1)
        return False

def convert_directory(directory, level=0):
    """递归转换目录下所有代码文件的编码"""
    success_count = 0
    total_count = 0
    
    # 确保目录路径是绝对路径
    directory = os.path.abspath(directory)
    
    # 获取相对于根目录的路径
    rel_path = os.path.basename(directory)
    print_with_indent(f"处理目录: {rel_path}/", level)
    
    # 分别处理文件和目录
    try:
        items = os.listdir(directory)
        files = [f for f in items if os.path.isfile(os.path.join(directory, f))]
        dirs = [d for d in items if os.path.isdir(os.path.join(directory, d))]
        
        # 先处理当前目录中的文件
        for file in sorted(files):
            if is_code_file(file):
                file_path = os.path.join(directory, file)
                total_count += 1
                print_with_indent(f"正在处理: {file}", level + 1)
                
                if convert_file_encoding(file_path):
                    success_count += 1
        
        # 然后递归处理子目录
        for dir_name in sorted(dirs):
            dir_path = os.path.join(directory, dir_name)
            sub_success, sub_total = convert_directory(dir_path, level + 1)
            success_count += sub_success
            total_count += sub_total
            
    except Exception as e:
        print_with_indent(f"错误: 处理目录 {directory} 时出错: {str(e)}", level + 1)
    
    return success_count, total_count

def main():
    # 检查命令行参数
    if len(sys.argv) != 2:
        print("使用方法: python gb2312_utf8.py <目录路径>")
        print("示例: python gb2312_utf8.py D:\\项目文件夹")
        return
    
    directory = sys.argv[1]
    
    # 检查目录是否存在
    if not os.path.exists(directory):
        print(f"错误: 目录 '{directory}' 不存在")
        return
    
    if not os.path.isdir(directory):
        print(f"错误: '{directory}' 不是一个目录")
        return
    
    print("\n开始批量转换文件编码（GB2312 -> UTF-8）...")
    success_count, total_count = convert_directory(directory)
    
    print("\n转换完成！")
    print(f"总计处理文件: {total_count} 个")
    print(f"成功转换: {success_count} 个")
    print(f"失败/跳过: {total_count - success_count} 个")

if __name__ == "__main__":
    main()